const { BrowserWindow, ipcMain, Menu, MenuItem, dialog, shell, app } = require('electron');
const http = require('http');
const fs = require('fs');
const path = require('path');

/** 打开本地文件 */
ipcMain.on('openFile', function (event, msg) {
    const data = JSON.parse(msg)
    console.log('打开本地文件', data.path);
    handleOpenFile(event, data.name, data.path);
});

ipcMain.on('show-error-dialog', function (event, msg) {
    dialog.showErrorBox(msg.title, msg.content);
});

ipcMain.on('show-right-click-menu', (event, data) => {
    const { show = [], ...params } = data;
    if (!show.length) return;
    // 生成右键菜单
    const menu = new Menu();
    if (show.includes('copy')) {
        menu.append(new MenuItem({
            label: '复制',
            // accelerator: 'CmdOrCtrl+C',
            role: 'copy'
        }));
    };
    if (show.includes('paste')) {
        menu.append(new MenuItem({
            label: '粘贴',
            // accelerator: 'CmdOrCtrl+V',
            role: 'paste'
        }));
    }
    if (show.includes('withdraw')) {
        menu.append(new MenuItem({
            label: '撤回',
            click: () => {
                event.sender.send('on-chat-msg-dispatch', { ...params, type: 'withdraw' });
            }
        }));
    };
    if (show.includes('settask')) {
        menu.append(new MenuItem({
            label: '设为任务',
            click: () => {
                event.sender.send('on-chat-msg-dispatch', { ...params, type: 'settask' });
            }
        }));
    }
    const win = BrowserWindow.fromWebContents(event.sender);
    menu.popup(win);
})

ipcMain.on('download', function (event, { files }) {
    var defaultPath = files.map(e=>e.filename).join()
    console.log(1,defaultPath);
    defaultPath = defaultPath.replace(/\//g, '-');
    const isOne = files.length === 1;
    const options = {
        defaultPath: defaultPath || '/未命名' // 文件名称项必填，windows上直接使用/是不会显示未命名的，mac会自动显示未命名
    };
    // 下载单个文件的时候默认显示文件名称和支持修改文件名称
    //if (isOne) options.defaultPath = `/${files[0].filename}`;

    const filenamePath = dialog.showSaveDialogSync(options);
    if (!filenamePath) return;
    files.forEach(d => {
        // 网络资源保存
        http.get(d.url, res => {
            res.setEncoding('binary');
            let fileData = '';
            res.on('data', chunk => {
                fileData += chunk;
            });
            const writePath = isOne ? filenamePath : path.join(filenamePath, `../${d.filename}`);
            res.on('end', () => {
                fs.writeFile(writePath, fileData, 'binary', err => {
                    if (err) {
                        event.sender.send('download-callback', { success: 0, msg: `${d.filename} 下载失败！` });
                        return
                    }
                    // 下载成功的回掉
                    event.sender.send('download-callback', { success: 1, msg: `${d.filename} 下载成功！` });
                });
            });
            res.on('error', e => {
                event.sender.send('download-callback', { success: 0, msg: `${d.filename} 下载失败！` });
            })
        });
    });
});

function handleOpenFile(event, filename, filePath) {
    const isOpenSuccess = shell.openItem(filePath);
    event.sender.send('open-item-callback', {
        success: isOpenSuccess ? 1 : 0,
        msg: `${filename || '文件'}打开${isOpenSuccess ? '成功' : '失败'}！`
    });
}

const previewDefaultData = {
    loading: false,
    loadingText: undefined,
    loadingPercent: 0,
    showloadingProgress: false
}

// 预览文件，先下载到本地，再通过shell使用默认方式打开文件
ipcMain.on('preview', function (event, file) {
    const { filename, newfilename, url } = file; // 聊天记录列表的预览没有filename
    if (!newfilename || newfilename.indexOf('null') !== -1) {
        event.sender.send('open-item-callback', { success: 0, msg: '文件格式有误！' });
        return;
    }
    // 检查目录是否存在
    // const dirPath = path.resolve(__dirname, '../../previewResources');
    const dirPath = app.getPath('downloads');
    const hasDir = fs.existsSync(dirPath);
    if (!hasDir) fs.mkdirSync(dirPath);
    // 检查文件是否存在
    const filePath = path.join(dirPath, `/${newfilename}`);
    const hasFile = fs.existsSync(filePath);
    if (hasFile) {
        handleOpenFile(event, filename, filePath);
        return;
    }
    event.sender.send('set-dashboard-state', {
        loading: true,
        loadingText: '正在加载文件，请稍后...',
        showloadingProgress: true
    });
    // 网络资源保存
    http.get(url, res => {
        const len = parseInt(res.headers['content-length'], 10);
        res.setEncoding('binary');
        let fileData = '';
        let current = 0;
        res.on('data', chunk => {
            fileData += chunk;
            current += chunk.length;
            event.sender.send('set-dashboard-state', { loadingPercent: (100.0 * current / len).toFixed(0) });
        });
        res.on('end', () => {
            fs.writeFile(filePath, fileData, 'binary', err => {
                if (err) {
                    event.sender.send('set-dashboard-state', previewDefaultData);
                    event.sender.send('open-item-callback', { success: 0, msg: `writeFile error: ${err.message}` });
                    return;
                }
                event.sender.send('set-dashboard-state', previewDefaultData);
                handleOpenFile(event, filename, filePath);
            });
        });
        res.on('error', err => {
            event.sender.send('set-dashboard-state', previewDefaultData);
            event.sender.send('open-item-callback', { success: 0, msg: `request error: ${err.message}` });
        });
    });
});